<template>
  <div class='calendar'>
    <div class='calendar-left'>
      <el-calendar ref="elcalendar">
        <template slot="dateCell" slot-scope="{date, data}">
          <div class="date-cell-div" @click="clickCal(data.day)">
            <p :class="data.isSelected ? 'is-selected' : ''">
              {{ data.day.substr(8, 2) }}
            </p>
            <i v-if="dealElCalendar(data)" style="width: 5px;height: 5px;border-radius:50%;background-color: red;display: block;margin: 15px 0 0 4px;"></i>
          </div>
        </template>
      </el-calendar>
      <div class="calendar-search">
        <el-select
          v-model="calendarInfo.calendarSearchValue"
          filterable
          clearable
          remote
          reserve-keyword
          placeholder="请输入日历名称"
          :remote-method="calendarRemoteMethod"
          :loading="loading"
          class="calendar-search-input"
          @change="calendarSearchChange">
          <el-option
            v-for="item in calendarInfo.calendarSearchOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <svg-icon iconClass="add" class="calendar-add-icon" @click.stop="openAddCalendar()"/>
      </div>
      <el-collapse v-model="calendarInfo.activeCollapse" class="calendar-collapse">
        <el-collapse-item title="我的日历" name="1">
          <div v-for="item in calendarInfo.calendarList" :key="item.id" class="calendar-collapse-div">
            <el-checkbox v-model="item.isChecked" @change="getScheduleList">{{item.calendarName}} {{ item.ownerId !== userInfo.userName ? '[共享]' : '' }}</el-checkbox>
            <el-popover
              placement="right"
              trigger="click"
              class="calender-handle-popover">
              <div class="calendar-setting-handle-div" @click.stop="openEditCalendar(item.id)">
                <i class="el-icon-edit-outline"></i>
                <span class="calendar-setting-handle-title">编辑</span>
              </div>
              <div class="calendar-setting-handle-div" @click.stop="openDeleteCalendar(item)">
                <i class="el-icon-delete"></i>
                <span class="calendar-setting-handle-title">删除</span>
              </div>
              <div class="calendar-setting-handle-div" @click.stop="openShareCalendar(item)">
                <i class="el-icon-share"></i>
                <span class="calendar-setting-handle-title">共享</span>
              </div>
              <i slot="reference" class="el-icon-setting calendar-setting-icon" v-if="item.ownerId === userInfo.userName"></i>
            </el-popover>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div class='calendar-right'>
      <FullCalendar
        ref="fullCalendar"
        class='calendar-full'
        :resources="resources"
        :options='calendarOptions'>
      </FullCalendar>
    </div>

    <!-- 新增日历弹窗 -->
    <div>
      <el-dialog :title="calendarInfo.title" :visible.sync="calendarInfo.addDialog" :close-on-click-modal="false">
        <el-form :model="calendarInfo.form" size="small">
          <el-form-item label="日历名称">
            <el-input v-model="calendarInfo.form.calendarName" placeholder="日历名称"></el-input>
          </el-form-item>
          <el-form-item label="日历描述">
            <el-input v-model="calendarInfo.form.calendarDesc" placeholder="日历描述" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="calendarInfo.addDialog" size="small" type="primary" id="copyBtn" @click="addCalendar($event)" data-clipboard-target="#pathText">保 存</el-button>
          <el-button size="small" @click="calendarInfo.addDialog = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 编辑日历弹窗 -->
    <div>
      <el-dialog :title="calendarInfo.title" :visible.sync="calendarInfo.editDialog" :close-on-click-modal="false">
        <el-form :model="calendarInfo.form" size="small">
          <el-form-item label="日历名称">
            <el-input v-model="calendarInfo.form.calendarName" placeholder="日历名称"></el-input>
          </el-form-item>
          <el-form-item label="日历描述">
            <el-input v-model="calendarInfo.form.calendarDesc" placeholder="日历描述" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="calendarInfo.editDialog" size="small" type="primary" id="copyBtn" @click="editCalendar($event)" data-clipboard-target="#pathText">保 存</el-button>
          <el-button size="small" @click="calendarInfo.editDialog = false, calendarInfo.form = {}">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 日历分享弹出框 -->
    <el-dialog title="选择共享权限角色" width='40%' :close-on-click-modal='false' :visible.sync="calendarInfo.shareDialog">
      <el-row  class="boxShadow">
        <el-col :span="11">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span style="font-size:14px;font-weight:bold;">选择只读权限角色</span>
            </div>
            <div>
              <el-tree  
                style="height:300px;overflow:auto;"
                :data="viewTreeData"
                show-checkbox
                default-expand-all
                :expand-on-click-node='false'
                check-on-click-node = 'true'
                node-key="id"
                ref="viewTree"
                highlight-current
                @check='checkTreeClick' 
                :default-checked-keys="viewTreeValue"
                :props="viewTreeProps">
              </el-tree>
            </div>
          </el-card>
        </el-col>
        <el-col :span="1">
        </el-col>
        <el-col :span="11">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span style="font-size:14px;font-weight:bold;">选择编辑权限角色</span>
            </div>
            <div>
              <el-tree  
                style="height:300px;overflow:auto;"
                :data="editTreeData"
                show-checkbox
                default-expand-all
                :expand-on-click-node='false'
                check-on-click-node = 'true'
                node-key="id"
                ref="editTree"
                highlight-current
                @check='checkTreeClick' 
                :default-checked-keys="editTreeValue"
                :props="editTreeProps">
              </el-tree>
            </div>
          </el-card>
        </el-col>
      </el-row> 
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="shareCalendar($event)" icon="el-icon-check">保 存</el-button>
        <el-button size="small" @click="calendarInfo.shareDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增、编辑日程弹窗 -->
    <div>
      <el-dialog title="日程" width="1100px" :visible.sync="scheduleInfo.scheduleVisible" :close-on-click-modal="false">
        <el-form :model="scheduleInfo.form" :rules="scheduleInfo.scheduleRules" ref="scheduleRuleForm" label-width="90px" size="medium" :inline="true">
          <el-form-item label="主题" prop="scheduleSubject" class="full-dialogFormItem">
            <el-input v-model="scheduleInfo.form.scheduleSubject" placeholder="请填写主题" :disabled="scheduleInfo.form.readFlag === '1'" class="full-input"></el-input>
          </el-form-item>
          <el-form-item label="时间" prop="dateRange" class="dialogFormItem">
            <el-date-picker
              v-model="scheduleInfo.form.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              align="right"
              :disabled="scheduleInfo.form.readFlag === '1'"
              class="half-input">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="日历" prop="calendarId" class="dialogFormItem">
            <el-select v-model="scheduleInfo.form.calendarId" placeholder="请选择日历" :disabled="scheduleInfo.form.readFlag === '1'" class="half-input">
              <el-option
                v-for="item in scheduleInfo.allCalendarOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日程内容" class="full-dialogFormItem">
            <el-input v-model="scheduleInfo.form.scheduleContent" placeholder="请填写日程内容" type="textarea" :autosize="{minRows: 3,maxRows: 5}" class="full-input" :disabled="scheduleInfo.form.readFlag === '1'"></el-input>
          </el-form-item>
          <el-form-item label="全天显示">
            <el-checkbox v-model="scheduleInfo.form.allDayShowFlag" :disabled="scheduleInfo.form.readFlag === '1'"></el-checkbox>
          </el-form-item>
          <el-form-item label="颜色">
            <el-color-picker v-model="scheduleInfo.form.color" size="small" :disabled="scheduleInfo.form.readFlag === '1'"></el-color-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="scheduleInfo.scheduleVisible && scheduleInfo.isAdd" size="small" type="primary" id="copyBtn" @click="addSchedule($event)" data-clipboard-target="#pathText">保 存</el-button>
          <el-button v-if="scheduleInfo.scheduleVisible && scheduleInfo.isEdit && scheduleInfo.form.readFlag !== '1'" size="small" type="primary" id="copyBtn" @click="editSchedule($event)" data-clipboard-target="#pathText">保 存</el-button>
          <el-button v-if="scheduleInfo.scheduleVisible && scheduleInfo.isEdit && scheduleInfo.form.readFlag !== '1'" size="small" type="danger" id="copyBtn" @click="deleteConferenceInfo" data-clipboard-target="#pathText">删除</el-button>
          <div   v-if="scheduleInfo.scheduleVisible && scheduleInfo.isEdit && scheduleInfo.form.readFlag !== '1'"  style="text-align:right; float:right">
              <el-button type="text"  icon="el-icon-time" style="font-weight:normal;" size="large" @click.stop="getHistoryRecord">修改历史</el-button>
          </div>  
          <el-button size="small" style="margin:0 10px"  id="copyBtn" @click="cancelSchedule()">取 消</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 历史记录 -->
    <update-history   ref="historyRecord"></update-history>
  </div>
</template>
<script>
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import momentPlugin from '@fullcalendar/moment' 
import listPlugin from '@fullcalendar/list';

import { INITIAL_EVENTS, createEventId } from '@/event-utils'
import 'bootstrap/dist/css/bootstrap.css';
import bootstrapPlugin from '@fullcalendar/bootstrap';

import {queryPermCalendarList, saveGeneralCalendarInfo, queryGeneralCalendarInfo, updateGeneralCalendarInfo, deleteGeneralCalendarInfo} from '@/api/general/calendar/generalCalendarInfoApi';
import {saveGeneralScheduleInfo,queryScheduleDuration, queryGeneralScheduleInfo, updateGeneralScheduleInfo,deleteGeneralScheduleInfo} from '@/api/general/schedule/generalScheduleInfoApi';
import {querySysRoleTree} from '@/api/system/sysRoleApi';
import {saveOrUpdateSysRolePrivilegeRelationList,querySysRolePrivilegeRelationListPage} from '@/api/system/sysRolePrivilegeRelationApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {dateFormat} from '@/util/date';

export default {

  components: {
    FullCalendar // make the <FullCalendar> tag available
  },

  data: function() {
    return {
      resources: [
        { id: 'a', title: 'Auditorium A' },
        { id: 'b', title: 'Auditorium B' },
        { id: 'c', title: 'Auditorium C' }
      ],
      calendarOptions: {
        plugins: [
          //resourceTimeGridPlugin,
          bootstrapPlugin,
          listPlugin, 
          momentPlugin,
          dayGridPlugin,
          timeGridPlugin,
          interactionPlugin // needed for dateClick
        ],
        schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
        themeSystem: 'bootstrap',
        headerToolbar: {
          left: 'prev,next,today',
          center: 'title',
          right: 'listWeek,dayGridMonth,timeGridWeek,timeGridDay'
        },
        initialView: 'dayGridMonth',
        
        initialEvents: INITIAL_EVENTS, // alternatively, use the `events` setting to fetch from a feed
        editable: true,
        selectable: true,
        selectMirror: true,
        dayMaxEvents: true,
        weekends: true,
        select: this.handleDateSelect,
        eventClick: this.handleEventClick,
        eventsSet: this.handleEvents,
        dateClick: this.handleDateClick,
        // dayCellDidMount: function(info) {
        //   //this.$console.log('info===',info);
        //   return 'test001'
        // },
        eventDidMount: function(info) {
          //$(info.el).tooltip({title: '11111'});             
          //this.$console.log('info===',info);
          // var tooltip = new Tooltip(info.el, {
          //   title: info.event.extendedProps.description,
          //   placement: 'top',
          //   trigger: 'hover',
          //   container: 'body'
          // });
        },
        eventRender: function(event, element) {
          element.attr('title', event.tip);
        },
        height: '100%',
        events:[], //日历信息列表
        buttonText: {
          allday: '整天',
          today: '今天',
          month: '月',
          week: '周',
          day: '天',
          listWeek:'周列表'
        },
        selectMirror: 'true',
        slotMinTime: '00:00:00',
        slotMaxTime: '24:00:00',
        selectable: 'true',
        locale: 'zh-cn', 
        slotEventOverlap: 'false',
        unselectAuto: 'false',
        selectOverlap: 'false',
        businessHours: [],
        firstDay: 1,
        allDaySlot: 'true',
        slotDuration: '00:30',
        slotLabelFormat: 'HH:mm',
        allDayContent: '全天',
        dayHeaderFormat:{
          weekday: 'short', 
          month: 'numeric', 
          day: 'numeric', 
          omitCommas: true 
        },
        // 随时判断时间是否合法，通过返回true/false来判断是否能够选择
        selectAllow: info => { 
          const currentDate = new Date()
          const start = info.start
          const end = info.end
          //this.$console.log('start,end===>', start.getYear(), start.getMonth(), start.getDay(),end, currentDate)
          return (start <= end && start >= currentDate) || (dateFormat(start).substring(0, 10) === dateFormat(currentDate).substring(0, 10))
        },
        eventMouseEnter: this.eventMouseEnter,
        //eventDragStop: this.eventDragStop,
        eventDrop: this.eventDragStop,
        eventResize: this.eventResize,

        dragOpacity:{
          agenda:.1, //对于agenda试图
          '':1.0 //其他视图
        },

        //dayCellContent: ''
        /* you can update a remote database when these fire:
        eventAdd:
        eventChange:
        eventRemove:
        */
      },
      currentEvents: [],
      // 日程控制
      scheduleInfo: {
        form: {
          scheduleSubject: '',
          dateRange: [],
          calendarId: ''
        },
        validFlag: false,
        scheduleVisible: false,
        allCalendarOptions: [],
        // 当前日期所在的时间段的开始时间和结束时间
        currentStartTime: '',
        currentEndTime: '',
        isAdd: false,
        isEdit: false,
        scheduleList: [],
        scheduleRules: {
          scheduleSubject: [
            { required: true, message: '请填写主题', trigger: 'blur' }
          ],
          dateRange: [
            { type: 'array', required: true, message: '请选择日期', trigger: 'change' }
          ],
          calendarId: [
            { required: true, message: '请选择日历', trigger: 'change' }
          ]
        }
      },
      // 日历控制
      calendarInfo: {
        calendarList: [],
        addDialog: false,
        editDialog: false,
        deleteDialog: false,
        shareDialog: false,
        title: '',
        form: {},
        shareForm: {
          readonlyRole: [],
          editAbleRole: []
        },
        activeCollapse: '1',
        deleteId: '',
        shareId: '',
        roleOptions: [],
        calendarSearchOptions: [],
        calendarSearchValue: '',
        hasScheDateList: []
      },
      viewTreeData: [],
      editTreeData: [],
      viewTreeValue:[],
      editTreeValue:[],
      viewTreeProps:  {
        label: 'roleName'
      },
      editTreeProps:  {
        label: 'roleName'
      },
      // 日历共享中间变量
      treeValue: [],
    }
  },
  computed: {
    ...mapGetters(['website','orgTree','userInfo','permission'])
  },
  watch: {
    // scheduleInfo: {
    //   handler(newData, oldData) {
    //     //this.$console.log('newData, oldData', newData, oldData)
    //     // if()
    //   },
    //   deep: true
    // }
  },
  created(){
    // 获取日历列表
    this.getCalendarList();
    // 查询角色
    this.getRoleTreeList();
  },
  mounted() {
    let _self = this;
    this.$nextTick(() => {
      // 修改element 日历控件样式
      let elPrevBtn = document.querySelector('.el-calendar__button-group .el-button-group>button:nth-child(1) span');
      elPrevBtn.innerHTML = '<';
      let elNextBtn = document.querySelector('.el-calendar__button-group .el-button-group>button:nth-child(3) span');
      elNextBtn.innerHTML = '>';

      // 监听fullcalendar的事件
      let fullCalDom = document.querySelectorAll('.fc-header-toolbar .fc-toolbar-chunk .btn-group >button');
      for(let button of fullCalDom){
        button.addEventListener('click', function() {
          _self.changeDurationTime();
        });
      }

      let calendarApi = this.$refs.fullCalendar.getApi()
      this.scheduleInfo.currentStartTime = dateFormat(new Date(calendarApi.view.currentStart));
      this.scheduleInfo.currentEndTime = dateFormat(new Date(calendarApi.view.currentEnd));

      // 获取日程
      this.getScheduleList('init');

      //获取业务字典
      setTimeout(() => {
        this.getSysParam();
      });
    });
  },
  methods: {
    /**
     * 调用子组件方法查询历史
     */
    getHistoryRecord () {
      setTimeout(() => {
        this.$refs.historyRecord.getUpdateHistoryRecord(this.scheduleInfo.form.id);
      })
    },
    // 修改日程查询的开始和结束日期
    changeDurationTime(){
      let calendarApi = this.$refs.fullCalendar.getApi()
      this.scheduleInfo.currentStartTime = dateFormat(new Date(calendarApi.view.activeStart));
      this.scheduleInfo.currentEndTime = dateFormat(new Date(calendarApi.view.activeEnd));
      this.getScheduleList();
    },
    // 处理element日历上的小红点
    dealElCalendar(data){
      if(this.calendarInfo.hasScheDateList.indexOf(data.day) !== -1){
        return true;
      }else{
        return false;
      }
    },

    handleWeekendsToggle() {
      this.calendarOptions.weekends = !this.calendarOptions.weekends // update a property
    },
    /**
     * 新增日程
     */
    handleDateSelect(selectInfo) {
      //this.$console.log('==selectInfo=',selectInfo.end);
      this.scheduleInfo.scheduleVisible = true;
      this.scheduleInfo.isAdd = true;
      this.scheduleInfo.isEdit = false;
      this.scheduleInfo.form.dateRange = []
      this.scheduleInfo.form.dateRange.push(selectInfo.start);
      this.scheduleInfo.form.dateRange.push(selectInfo.end);
    },

    handleEventClick(clickInfo) {
      this.$console.log('handleEventClick===>', clickInfo.event.id)
      let reqParams =  {
        singleBody: {
          id: clickInfo.event.id
        }
      }
      let commonData = reqCommonMsg(reqParams)
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      });
      queryGeneralScheduleInfo(commonData).then(res => {
        let result = res.data.body.singleBody;
        if(result.allDayShowFlag === '0'){
          result.allDayShowFlag = false;
        }else if(result.allDayShowFlag === '1'){
          result.allDayShowFlag = true;
        }else{
          result.allDayShowFlag = false;
        }

        // 判断是否为只读
        this.calendarInfo.calendarList.map(item => {
          if(item.id === result.calendarId){
            result.readFlag = item.readFlag
          }
        })

        let dateRange = [new Date(result.scheduleBeginDatetime), new Date(result.scheduleEndDatetime)]
        result.dateRange = dateRange;

        this.scheduleInfo.form = result;
        this.scheduleInfo.scheduleVisible = true;
        this.scheduleInfo.isAdd = false;
        this.scheduleInfo.isEdit = true;
        loading.close();
      }, error => {
        //this.$console.log(error);
        loading.close();
      });
    },

    handleEvents(events) {
      this.currentEvents = events
    },
    eventMouseEnter(events){
      //this.$console.log('events==',events)
    },
    handleDateClick: function(arg) {
      //this.$console.log('date click! ' + arg.dateStr)
    },
    // 拖动日程停止后事件
    eventDragStop: function( event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view ) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      });

      // 判断修改前后相差多少天
      let oldStart = event.oldEvent.start;
      let start = event.event.start;
      let diffDay = (start.getTime() - oldStart.getTime())/(1000 * 60 * 60 * 24)
      //this.$console.log('diffDay===>', diffDay);

      // 拖动日程，修改日程日期
      let scheduleId = event.event.id;
      let schedule = {};
      this.scheduleInfo.scheduleList.map(item => {
        if(scheduleId === item.id){
          schedule = item;
          schedule.scheduleBeginDatetime = dateFormat(new Date(new Date(schedule.scheduleBeginDatetime).getTime() + (diffDay * (1000 * 60 * 60 * 24))));
          schedule.scheduleEndDatetime = dateFormat(new Date(new Date(schedule.scheduleEndDatetime).getTime() + (diffDay * (1000 * 60 * 60 * 24))));
        }
      });

      // 修改日程日期
      delete schedule.readFlag;
      let reqParams = {
        singleBody: schedule
      };
      let commonData = reqCommonMsg(reqParams);
      updateGeneralScheduleInfo(commonData).then(() => {
        this.scheduleInfo.form = {};
        this.scheduleInfo.scheduleVisible = false;
        this.scheduleInfo.isAdd = false;
        this.scheduleInfo.isEdit = false;
        this.getScheduleList();
        loading.close();
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading.close();
      });
    },
    // 调整日程大小修改日期
    eventResize(event){
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      });

      // 判断修改前后相差多少天
      let oldStart = event.oldEvent.start;
      let start = event.event.start;
      let startDiffDay = (start.getTime() - oldStart.getTime())/(1000 * 60 * 60 * 24)
      //this.$console.log('startDiffDay===>', startDiffDay);
      let oldEnd = event.oldEvent.end;
      let end = event.event.end;
      let endDiffDay = (end.getTime() - oldEnd.getTime())/(1000 * 60 * 60 * 24)
      //this.$console.log('endDiffDay===>', endDiffDay);

      // 拖动日程，修改日程日期
      let scheduleId = event.event.id;
      let schedule = {};
      this.scheduleInfo.scheduleList.map(item => {
        if(scheduleId === item.id){
          schedule = item;
          schedule.scheduleBeginDatetime = dateFormat(new Date(new Date(schedule.scheduleBeginDatetime).getTime() + (startDiffDay * (1000 * 60 * 60 * 24))));
          schedule.scheduleEndDatetime = dateFormat(new Date(new Date(schedule.scheduleEndDatetime).getTime() + (endDiffDay * (1000 * 60 * 60 * 24))));
        }
      });

      // 修改日程日期
      delete schedule.readFlag;
      let reqParams = {
        singleBody: schedule
      };
      let commonData = reqCommonMsg(reqParams);
      updateGeneralScheduleInfo(commonData).then(() => {
        this.scheduleInfo.form = {};
        this.scheduleInfo.scheduleVisible = false;
        this.scheduleInfo.isAdd = false;
        this.scheduleInfo.isEdit = false;
        this.getScheduleList();
        loading.close();
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading.close();
      });
    },

    clickCal(clickDate){
      let calendarApi = this.$refs.fullCalendar.getApi()
      calendarApi.gotoDate(new Date(clickDate));

      if(this.scheduleInfo.currentStartTime !== dateFormat(new Date(calendarApi.view.currentStart)) 
        || this.scheduleInfo.currentEndTime !== dateFormat(new Date(calendarApi.view.currentEnd))){
        this.changeDurationTime();
      }
      // 跳转月份
      // this.$refs.elcalendar.selectDate('prev-month')
    },
    // 获取日历列表
    getCalendarList(){
      let singleBody = {
        ownerId: this.userInfo.userName
      };
      let reqParams =  {
        singleBody: singleBody
      }
      let commonData = reqCommonMsg(reqParams)
      queryPermCalendarList(commonData).then(res => {
        let result = res.data.body.listBody;
        if(result){
          result.forEach(item => {
            this.scheduleInfo.allCalendarOptions.push({
              label: item.ownerId === this.userInfo.userName? item.calendarName : item.calendarName + '[共享]',
              value: item.id,
              disabled: item.readFlag === '1' ? true: false
            });
            item.isChecked = true;
          });
          this.calendarInfo.calendarList = result;
          this.calendarInfo.hasScheDateList = res.data.body.singleBody.dateList;
        }
      }, error => {
      });
    },
    // 打开新增日历弹窗
    openAddCalendar(){
      this.calendarInfo.title = '新增日历'
      this.calendarInfo.addDialog = true;
    },
    // 保存日历
    addCalendar(){
      this.calendarInfo.form.ownerId = this.userInfo.userName
      let reqParams = {
        singleBody: this.calendarInfo.form
      };
      let commonData = reqCommonMsg(reqParams)
      saveGeneralCalendarInfo(commonData).then(() => {
        this.calendarInfo.addDialog = false;
        this.calendarInfo.form = {};
        this.getCalendarList();
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
      });
    },
    // 打开编辑日历弹窗
    openEditCalendar(id){
      this.calendarInfo.title = '编辑日历'
      let reqParams =  {
        singleBody: {
          id: id
        }
      }
      let commonData = reqCommonMsg(reqParams)
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      });
      queryGeneralCalendarInfo(commonData).then(res => {
        this.calendarInfo.form = res.data.body.singleBody;
        this.calendarInfo.editDialog = true;
        loading.close();
      }, error => {
        //this.$console.log(error);
        loading.close();
      });
    }, 
    // 编辑 保存日历
    editCalendar(){
      let reqParams = {
        singleBody: this.calendarInfo.form
      };
      let commonData = reqCommonMsg(reqParams)
      updateGeneralCalendarInfo(commonData).then(() => {
        this.calendarInfo.editDialog = false;
        this.calendarInfo.form = {};
        this.getCalendarList();
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
      });
    },
    // 删除日历
    openDeleteCalendar(row){
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let reqParams = {
          singleBody: row
        };
        let commonData = reqCommonMsg(reqParams);
        return deleteGeneralCalendarInfo(commonData);
      }).then(() => {
        this.getCalendarList();
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }).catch(() => {});
    },
    // 打开分享对话框
    openShareCalendar(row){
      this.calendarInfo.title = '分享日历'
      this.calendarInfo.shareId = row.id
      // 查询日历的共享信息
      this.getCheckedResource('5', row.id);
    },
    /**
     * 判断列表是否发生了变化
     */
    changedList(readFlag){
      this.treeValue=[];
      let resultList = [];
      // 判断当前活动tab
      if(readFlag == '1'){
        this.treeValue = this.$refs.viewTree.getCheckedKeys(true);
        //this.treeValue.push(...this.$refs.menuTree.getHalfCheckedKeys());
      }
      else if(readFlag == '2'){
        this.treeValue = this.$refs.editTree.getCheckedKeys(true);
        //this.treeValue.push(...this.$refs.interfaceTree.getHalfCheckedKeys());
      }
      // 前后选择对比，给新增和删除的打上标识
      // 原列表不存在的表示新增的元素
      let inOldValue = false;
      let inNewValue = false;
      this.treeValue.forEach(element => {
        inOldValue = false;
        for(var i = 0 ; i < this.oldTreeValue.length; i++){
          if (element == this.oldTreeValue[i]) {
            inOldValue = true;
            i = this.oldTreeValue.size + 1;
          }
        }
        //若没找到表示新增元素
        if(!inOldValue){
          resultList.push({
            resourceType: '5',
            roleId: element,
            resourceId: this.calendarInfo.shareId,
            readFlag: readFlag,
            validFlag: '1'
          })
        }
      });

      //新列表中不存在 表示 删除元素
      this.oldTreeValue.forEach(element => {
        inNewValue = false;
        for(var i = 0 ; i < this.treeValue.length; i++){
          if (element == this.treeValue[i]) {
            inNewValue = true;
            i = this.treeValue.size + 1;
          }
        }
        //若没找到表示删除元素
        if(!inNewValue){
          resultList.push({
            resourceType: '5',
            roleId: element,
            resourceId: this.calendarInfo.shareId,
            readFlag: readFlag,
            validFlag: '0'
          })
        }
      });
      return resultList;
    },
    // 保存分享
    async shareCalendar(){
      if(this.checkTreeClick('',true,'')){
        return false;
      }

      // 计算可读权限列表
      this.oldTreeValue = this.oldViewTreeValue;
      let resultList = await this.changedList('1');
      // 计算可编辑权限列表
      this.oldTreeValue = this.oldEditTreeValue;
      let editResultList = await this.changedList('2');
      resultList.push(...editResultList);
      if(resultList.length > 0){
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
        });
        let reqParams =  {
          transCode: '0001',
          listBody: resultList
        }
        let commonData = reqCommonMsg(reqParams)
        saveOrUpdateSysRolePrivilegeRelationList(commonData).then(() => {
          this.calendarInfo.shareDialog = false;
          this.calendarInfo.shareForm = {};
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
        }, error => {
          //this.$console.log(error);
          loading.close();
        });
      }
      else{
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '未发生变化,无需保存!'
        });
        this.fullscreenLoading = false;
      }
    },
    /**
     * 获取角色列表，只获取 roleType = 5 （日历类型）的 
     */
    async getRoleTreeList(){
      // 加载树形目录列表
      let reqParams =  {
        singleBody: {
          roleType: '5'
        },
        currentPage: 1, 
        pageSize: 100
      }
      let commonData = reqCommonMsg(reqParams)
      await querySysRoleTree(commonData).then(res => {
        this.viewTreeData= res.data.body.listBody;
        this.editTreeData= res.data.body.listBody;
      }, error => {
      });
    },
    /**
     * 获取已选择的资源权限
     */
    async getCheckedResource(type,id){
      let reqParams =  {
        singleBody: {
          resourceType : type,
          resourceId: id
        },
        currentPage: 1, 
        pageSize: 100
      }
      let commonData = reqCommonMsg(reqParams)
      await querySysRolePrivilegeRelationListPage(commonData).then(res => {
        this.viewTreeValue = [];
        this.editTreeValue = [];
        res.data.body.listBody.forEach(element => {
          //只读
          if(element.readFlag == '1'){
            this.viewTreeValue.push(element.roleId);
          }
          //可编辑
          else if(element.readFlag == '2'){
            this.editTreeValue.push(element.roleId);
          }
        });
        this.oldViewTreeValue=[];
        this.oldEditTreeValue=[];
        this.oldViewTreeValue = this.deepClone(this.viewTreeValue)
        this.oldEditTreeValue = this.deepClone(this.editTreeValue)

        this.calendarInfo.shareDialog = true;
      }, error => {
      });
    },
    /**
     * 查看被点击
     */
    checkTreeClick(data,node,self){
      let hasFound = false;
      let viewValue = this.$refs.viewTree.getCheckedKeys(true);
      let editValue = this.$refs.editTree.getCheckedKeys(true);
      viewValue.forEach(element => {
        editValue.forEach(editElement => {
          if(element == editElement){
            hasFound = true;
          }
        });
      });
      if(hasFound){
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: '该目录不能同时选择两个相同的角色!'
        });
      }
      return hasFound;
    },

    // 新增、修改前，处理日程信息
    dealScheduleInfo(){
      let singleBody = this.deepClone(this.scheduleInfo.form);
      //this.$console.log('singleBody=====>', singleBody)
      singleBody.scheduleBeginDatetime = dateFormat(new Date(singleBody.dateRange[0]));
      singleBody.scheduleEndDatetime = dateFormat(new Date(singleBody.dateRange[1]));
      singleBody.ownerUserName =  this.userInfo.userName;
      if(singleBody.allDayShowFlag){
        singleBody.allDayShowFlag = '1';
      }else{
        singleBody.allDayShowFlag = '0';
      }
      let reqParams = {
        singleBody: singleBody
      };
      return reqCommonMsg(reqParams);
    },
    
    // 校验日程信息
    validScheduleInfo(){
      this.$refs['scheduleRuleForm'].validate((valid) => {
        //this.$console.log('valid======>', valid)
        if (valid) {
          this.scheduleInfo.validFlag = true;
        } else {
          this.scheduleInfo.validFlag = false;
        }
      });
    },
    // 重置日程form校验
    resetScheduleForm() {
      this.$refs['scheduleRuleForm'].resetFields();
    },
    // 取消日程对话框
    cancelSchedule(){
      this.scheduleInfo.scheduleVisible = false;
      this.scheduleInfo.form = {};
      this.scheduleInfo.isAdd = false;
      this.scheduleInfo.isEdit = false;
      this.resetScheduleForm();
    },
    // 新增日程
    addSchedule(){
      this.validScheduleInfo();

      if(this.scheduleInfo.validFlag){
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading'
        });
  
        // 处理日程信息
        let commonData = this.dealScheduleInfo();
        saveGeneralScheduleInfo(commonData).then(() => {
          this.scheduleInfo.form = {};
          this.scheduleInfo.scheduleVisible = false;
          this.scheduleInfo.isAdd = false;
          this.scheduleInfo.isEdit = false;
          this.scheduleInfo.validFlag = false;
          this.resetScheduleForm();
          this.getScheduleList();
          loading.close();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        }, error => {
          //this.$console.log(error);
          loading.close();
        });      
      }
    },

    // 修改日程信息
    editSchedule(){
      //this.$console.log('editSchedule=======>');
      this.validScheduleInfo();
      if(this.scheduleInfo.validFlag){
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading'
        });
  
        // 处理日程信息
        let commonData = this.dealScheduleInfo();
        updateGeneralScheduleInfo(commonData).then(() => {
          this.scheduleInfo.form = {};
          this.scheduleInfo.scheduleVisible = false;
          this.scheduleInfo.isAdd = false;
          this.scheduleInfo.isEdit = false;
          this.scheduleInfo.validFlag = false;
          this.resetScheduleForm();
          this.getScheduleList();
          loading.close();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        }, error => {
          //this.$console.log(error);
          loading.close();
        });
      }
    },
    /**
     * 删除会议
     */
    deleteConferenceInfo(){
      this.$confirm('确定要删除当前日程?', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'})
        .then(() => {
          return deleteGeneralScheduleInfo(reqCommonMsg({singleBody:this.scheduleInfo.form}));
        })
        .then(() => {
          this.getScheduleList();
          this.scheduleInfo.scheduleVisible = false;
          this.$message({type: 'success',message: '删除成功!'});
        }).catch(() => {});
    },
    // 查询日程信息
    getScheduleList(val){
      let scheduleList = [];
      let noCalendarFlag = true;
      this.calendarInfo.calendarList.forEach(item => {
        if(item.isChecked){
          scheduleList.push({
            calendarId: item.id
          });
          noCalendarFlag = false;
        }
      });

      if(noCalendarFlag && 'init' !== val){
        this.$message({
          type: 'warning',
          message: '必须选择一个日历!'
        });
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      });

      let singleBody = {
        scheduleBeginDatetime: this.scheduleInfo.currentStartTime,
        scheduleEndDatetime: this.scheduleInfo.currentEndTime
      };
      if('init' === val){
        singleBody.id = val;
      }

      let reqParams = {
        singleBody: singleBody,
        listBody: scheduleList
      };
      let commonData = reqCommonMsg(reqParams)
      queryScheduleDuration(commonData).then(res => {
        let result = res.data.body.listBody;
        if(result.length > 0){
          this.calendarOptions.events = [];
          result.forEach(item => {
            let allDay = false;
            let end = item.scheduleEndDatetime;
            if(item.allDayShowFlag === '0'){
              allDay = false;
            }else if(item.allDayShowFlag === '1'){
              allDay = true;
              if(item.scheduleEndDatetime.substring(11, 19) !== '00:00:00'){
                end = new Date(new Date(item.scheduleEndDatetime).getTime() + 1000 * 60 * 60 * 24);
                //this.$console.log('end===>', end)
              }
            }
            this.calendarOptions.events.push({
              id: item.id,
              description: item.scheduleContent,
              title: item.scheduleSubject,
              start: item.scheduleBeginDatetime,
              end: end,
              color: item.color,
              allDay: allDay
            })
          });
        }
        else{
          //改写No Event To Display;
          var ele =document.getElementsByClassName('fc-list-empty-cushion');
          if(ele.length > 0){
            setTimeout(() => {
              ele[0].innerText = '没有更多数据！';
            }, 100);
          }
        }
        // 保存当前页面上的日程信息
        this.scheduleInfo.scheduleList = result;
        loading.close();
      }, error => {
        //this.$console.log(error);
        loading.close();
      });
    },

    // 日历搜索框
    calendarRemoteMethod(query) {
      if (query !== '') {
        setTimeout(() => {
          this.calendarInfo.calendarSearchOptions = [];

          let result = this.calendarInfo.calendarList.filter(item => {
            return item.calendarName.indexOf(query) !== -1;
          });

          if(result){
            result.map(item => {
              this.calendarInfo.calendarSearchOptions.push({
                label: item.calendarName,
                value: item.id
              });
            })
          }
        }, 200);
      } else {
        this.calendarInfo.calendarSearchOptions = [];
      }
    },
    // 搜索日历后，触发勾选日历
    calendarSearchChange(val){
      this.calendarInfo.calendarList.map(item => {
        if(item.id === val && item.isChecked === false){
          item.isChecked = true;
          this.getScheduleList();
        }
      })
    },
    /**
     * 获取工作日参数
     */
    async getSysParam() {
      let sysParamData = await this.$params.getSysParam('calendarWorkdayParam');
      if(sysParamData){
        let businessHours = JSON.parse(sysParamData.calendarWorkdayParam);
        this.calendarOptions.businessHours = businessHours
        //this.$console.log('this.calendarOptions.businessHours===>', this.calendarOptions.businessHours)
      }
    }
  }
}
</script>
<style lang='css'>
.calendar {
  display: flex;
  min-height: 100%;
  font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
  font-size: 14px;
  background-color: #fff;
}
.calendar .el-calendar__header{
  padding: 12px 10px;
}
.calendar .el-calendar__header .el-calendar__button-group{
  width: 35%;
  text-align: right;
}
.calendar .el-calendar__header .el-calendar__button-group .el-button-group > button:nth-of-type(1){
  width: 20%;
  border: 0;
  padding: 5px 10px 5px 5px;
  font-size: 12px;
}
.calendar .el-calendar__header .el-calendar__button-group .el-button-group > button:nth-of-type(2){
  border: 0;
  padding: 5px 5px 5px 5px;
}
.calendar .el-calendar__header .el-calendar__button-group .el-button-group > button:nth-of-type(3){
  width: 20%;
  border: 0;
  padding: 5px 5px 5px 5px;
}

.is-selected {
  color: #1989FA;
}

.calendar-right {
  flex-grow: 1;
  padding: 1em;
  height: 100%;
}

.fc { /* the calendar root */
  /* max-width: 1100px; */
  margin: 0 auto;
}
.calendar-right .fc-header-toolbar .btn{
  line-height: 1 !important;
}
.calendar-left{
  max-width: 350px;
  padding: 20px;
}

.calendar .calendar-left .el-calendar-table .el-calendar-day {
  box-sizing: border-box;
  padding: 0;
  height: 4em;
  font-size: 10px;
  line-height: 40px;
  text-align: center;
  display: flex;
  justify-content: center;
}

.calendar .calendar-left .el-calendar-table thead th {
  padding: 12px 0;
  color: #606266;
  font-weight: 400;
  text-align: center;
}

.calendar .calendar-left .el-calendar .el-calendar__body {
  padding: 12px 10px 20px;
}

.is-selected {
  color: #1989FA;
}

.calendar-collapse .el-collapse-item__header{
  color: #9f9e9e;
  font-weight: bold;
  font-size: 15px;
}

.calendar-collapse-div{
  padding: 5px 0 5px 1em;
  display: flex;
  justify-content: left;
}

.calendar-search {
  display: flex;
  margin: 0 0 15px 0;
}

.calendar-search .el-select {
  width: -webkit-fill-available;
}

.calendar-search .el-select .el-input{
  border-bottom: 0!important;
}

.calendar-search-input .el-input__inner {
  border-radius: 25px;
  height: 30px;
  line-height: 40px;
}
.calendar-setting-icon{
  cursor: pointer;
  font-size: 20px;
  margin: 0 0 0 15px;
  line-height: 1.2em;
}
.calendar-setting-icon:hover{
  border: 1px solid #cccccc;
  border-radius: 3px;
  background-color: #f1f1f1;
}

.calendar-add-icon {
  display: block;
  font-size:15px;
  height: 2em!important;
  margin: 0 0 0 10px;
  cursor:pointer;
}
.calendar-add-icon:hover{
  border: 1px solid #cccccc;
  border-radius: 3px;
  background-color: #f1f1f1;
}

.calendar-setting-handle-div{
  cursor:pointer;
  margin: 5px 0 5px 0;
}
.calendar-setting-handle-div:hover{
  border: 1px solid #cccccc;
  border-radius: 3px;
  background-color: #f1f1f1;
}

.calendar-setting-handle-title{
  margin: 0 0 0 15px;
}

.el-popover{
  min-width: 100px!important;
}

.calendar-collapse .el-collapse-item__wrap{
  border-bottom: 0;
}
.calendar-collapse .el-collapse-item__content{
  padding-bottom: 10px;
}

.calendar-collapse-calender-name{
  cursor: pointer;
}
.calendar-collapse-calender-name:hover{
  border: 1px solid #cccccc;
  border-radius: 3px;
  background-color: #f1f1f1;
}

.date-cell-div{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}

.calendar .el-input{
  border-bottom: 0!important;
}

.calendar .dialogFormItem{
  width: 510px;
}

.calendar .dialogFormItem .half-input .el-input__inner{
  width: 380px;
}
.calendar .mini-dialogFormItem .mini-input .el-input__inner{
  width: 120px;
}
.calendar .full-dialogFormItem .full-input .el-input__inner{
  width: 900px;
}
.calendar .full-dialogFormItem .full-input .el-textarea__inner{
  width: 900px;
}
</style>